package game.utils
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.core.LoaderCore;
	
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	
	/**
	 * 自定义loader类
	 * @author xiezhicheng
	 */
	public class MassLoader
	{
		private static var _instance:MassLoader;
		
		private var _loader:LoaderMax;
		/**完成回调函数*/
		private var _completeFun:Function;
		/**进度回调函数*/
		private var _progressFun:Function;
		/**域*/
		private var context:LoaderContext;
		
		public function MassLoader()
		{
			if (_instance == null) 
			{
				_instance = this;
				init();
			
			}else{
				throw new Error("MassLoader is a single class");
			}
			
		}
		
		/**
		 * 创建实例
		 * @return 
		 */
		public static function getInstance():MassLoader
		{
			if (_instance == null) 
			{
				_instance = new MassLoader();
			}	
			return _instance;
			
		}
		
		
		private function init():void
		{
			context = new LoaderContext();
			context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
			context.securityDomain = SecurityDomain.currentDomain;
			LoaderMax.defaultContext = context;
			_loader = new LoaderMax({onProgress:progressHandler,onComplete:completeHandler});	
		}
		
		
		/**
		 * 添加loader
		 * @param arr
		 */
		public function append(arr:Array):void
		{
			while(arr.length>0)
			{
				_loader.append(arr.pop());
			}
			_loader.load();
		}
		
		
		private function progressHandler(e:LoaderEvent):void
		{
			if (_progressFun != null) 
			{
				_progressFun(e);
			}
			
		}
		
		
		private function completeHandler(e:LoaderEvent):void
		{
			if (_completeFun != null) 
			{
				_completeFun();
			}	
			
		}
		
		
		/**
		 * 设置进度回调函数
		 * @param value
		 */
		public function set progress(value:Function):void
		{
			if (value != null) 
			{
				_progressFun = value;
			}		
		}

		
		/**
		 * 设置完成回调函数
		 * @param value
		 */
		public function set complete(value:Function):void
		{
			if (value != null) 
			{
				_completeFun = value;
			}	
		}

		/**
		 * 
		 * @return 
		 */
		public function get loader():LoaderMax
		{
			return _loader;
		}
		
		
		public function removeLoader(name:String):void
		{
			if (!name || name=="") 
			{
				return;
			}
			_loader.remove(_loader.getLoader(name));
		}
		
	}
}